{include file='pub/header'/}
<title>编辑商品</title>
<link href="__STATIC__/lib/webuploader/0.1.5/webuploader.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page-container">
	<form class="form form-horizontal" id="form-product-add">
		<input type="hidden" name="id" value="{$product.id}">
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>分类：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<span class="select-box" style="width: 300px;">
					<select id="cateId1" class="select" size="1"></select>
				</span>
				<span class="select-box" style="width: 300px;">
					<select id="cateId2" name="cateId" class="select" size="1"></select>
				</span>
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>产品名称：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="{$product['name']}" placeholder="" name="name">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>单价：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="{$product['cost']}" placeholder="" name="cost">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>单位：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="{$product['goodattr']}" placeholder="" name="goodattr">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>规格：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<input type="text" class="input-text" value="{$product['guige']}" placeholder="" name="guige">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2"><span class="c-red">*</span>是否是组合商品：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<span class="select-box">
					<select name="combine_sta" class="select">
						<option value="0" {if condition="$product['combine_sta'] eq 0"} selected {/if}>
							否
						</option>
						<option value="1" {if condition="$product['combine_sta'] eq 1"} selected {/if}>
							是
						</option>
					</select>
				</span>
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2">商品展示图：</label>
			<div class="formControls col-xs-8 col-sm-9">
				<div class="uploader-thum-container">
					<div id="fileList" class="uploader-list">
						{foreach :explode(',', $product['img']) as $key=>$item}
						<div id="e{$key}" class="item" style="float: left; margin-left: 2px;">
							<div class="pic-box" style="position: relative;">
								<p style="width: 100%; background-color: rgba(180,180,180,0.8); text-align: right; color: #fff; position: absolute;">
									<i class="Hui-iconfont" onclick="dropPic(this)">&#xe6a6;</i>
								</p>
								<img src="{$item}" style="width: 100px; height: 100px;">
							</div>
							<div class="info"></div>
						</div>
						<input type="hidden" name="img[]" value="{$item}" class="e{$key}"/>
						{/foreach}
					</div>
					<div id="filePicker">选择图片</div>
				</div>
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2">商品详情：</label>
			<div class="formControls col-xs-8 col-sm-9">
                <script id="editor" name="instro" type="text/plain" style="width:100%;height:400px;">{$product['instro']}</script>;
			</div>
		</div>
		<div class="row cl">
			<div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">
				<button class="btn btn-secondary radius" type="submit"><i class="Hui-iconfont">&#xe632;</i> 保存商品</button>
				<button onClick="layer_close();" class="btn btn-default radius" type="button">&nbsp;&nbsp;取消&nbsp;&nbsp;</button>
			</div>
		</div>
	</form>
</div>


{include file="pub/footer"/}
<script type="text/javascript" src="__STATIC__/lib/webuploader/0.1.5/webuploader.min.js"></script>
<script type="text/javascript" src="__STATIC__/lib/ueditor/1.4.3/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/lib/ueditor/1.4.3/ueditor.all.min.js"> </script>
<script type="text/javascript" src="__STATIC__/lib/ueditor/1.4.3/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">

$(function(){
    var ue = UE.getEditor('editor');


	//动态添加分类 开始
    var $cateTree = {:json_encode($cateTree)};
    var opts = '';
    $.each($cateTree, function(i, v){
       opts += '<option value="'+i+'" ind="'+v.id+'">'+v.name+'</option>';
	});
    $("#cateId1").html(opts);
    $("#cateId1").find('option[ind="{$pid}"]').attr('selected', true);
    var cateId = $("#cateId1").val();
    var opts1= '';
    $.each($cateTree[cateId].children, function (i1,v1) {
        opts1 += '<option value="'+v1.id+'">'+v1.name+'</option>';
    });
    $("#cateId2").html(opts1);
    $("#cateId2").find('option[value="{$product[\'cateId\']}"]').attr('selected', true);
    $("#cateId1").on('change', function () {
		var id = $(this).val();
		var opts2 = "";
		$.each($cateTree[id].children, function (i1,v1) {
			opts2 += '<option value="'+v1.id+'">'+v1.name+'</option>';
        });
		$("#cateId2").html(opts2);
    });
	//动态添加分类  结束

    $('.skin-minimal input').iCheck({
        checkboxClass: 'icheckbox-blue',
        radioClass: 'iradio-blue',
        increaseArea: '20%'
    });
	var $list = $("#fileList"),
	$btn = $("#btn-star"),
	state = "pending";
	var uploader = WebUploader.create({
		auto: true,
		swf: '__STATIC__/lib/webuploader/0.1.5/Uploader.swf',
		// 文件接收服务端。
		server: '{:url("Product/addProductImg")}',
		// 选择文件的按钮。可选。
		// 内部根据当前运行是创建，可能是input元素，也可能是flash.
		pick: '#filePicker',
		// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
		resize: false,
		// 只允许选择图片文件。
		accept: {
			title: 'Images',
			extensions: 'gif,jpg,jpeg,bmp,png',
			mimeTypes: 'image/*'
		},
        //fileNumLimit:1
	});
	uploader.on( 'fileQueued', function( file ) {
        var $li = $(
            '<div id="' + file.id + '" class="item" style="float: left; margin-left: 2px;">' +
            '<div class="pic-box" style="position: relative;"><p style="width: 100%; background-color: rgba(180,180,180,0.8); text-align: right; color: #fff; position: absolute;"><i class="Hui-iconfont" onclick="dropPic(this)">&#xe6a6;</i></p><img></div>'+
            '<div class="info">' + file.name + '</div>' +
            '<p class="state">等待上传...</p>'+
            '</div>'
            ),
        $img = $li.find('img');
        $list.append( $li );
		// 创建缩略图
		// 如果为非图片文件，可以不用调用此方法。
		// thumbnailWidth x thumbnailHeight 为 100 x 100
		uploader.makeThumb( file, function( error, src ) {
			if ( error ) {
				$img.replaceWith('<span>不能预览</span>');
				return;
			}
			$img.attr( 'src', src );
		}, 100, 100);
	});
	// 文件上传过程中创建进度条实时显示。
	uploader.on( 'uploadProgress', function( file, percentage ) {
		var $li = $( '#'+file.id ),
			$percent = $li.find('.progress-box .sr-only');
	
		// 避免重复创建
		if ( !$percent.length ) {
			$percent = $('<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>').appendTo( $li ).find('.sr-only');
		}
		$li.find(".state").text("上传中");
		$percent.css( 'width', percentage * 100 + '%' );
	});
	
	// 文件上传成功，给item添加成功class, 用样式标记上传成功。
	uploader.on( 'uploadSuccess', function( file, res ) {
		$( '#'+file.id ).addClass('upload-state-success').find(".state").text("已上传");
		if(res.code == 1){
            // var img = res.data;
            var img = "<input type='hidden' class='"+file.id+"' name='img[]' value='" + res.data + "'/>";
		    $("#form-product-add").append(img);
		}
	});
	
	// 文件上传失败，显示上传出错。
	uploader.on( 'uploadError', function( file ) {
		$( '#'+file.id ).addClass('upload-state-error').find(".state").text("上传出错");
	});
	
	// 完成上传完了，成功或者失败，先删除进度条。
	uploader.on( 'uploadComplete', function( file ) {
		$( '#'+file.id ).find('.progress-box').fadeOut();
		uploader.reset();
	});
	uploader.on('all', function (type) {
        if (type === 'startUpload') {
            state = 'uploading';
        } else if (type === 'stopUpload') {
            state = 'paused';
        } else if (type === 'uploadFinished') {
            state = 'done';
        }

        if (state === 'uploading') {
            $btn.text('暂停上传');
        } else {
            $btn.text('开始上传');
        }
    });

    $btn.on('click', function () {
        if (state === 'uploading') {
            uploader.stop();
        } else {
            uploader.upload();
        }
    });

    $("#form-product-add").validate({
        rules:{
            name:{
                required:true
            },
			cost:{
                required:true,
				number:true,
				min:0
			},
			goodattr:{
                required:true
			},
			guige:{
                required:true
			},
			'img[]':{
                required:true,
				min:1
			}
        },
		messages:{
            name:{
                required:'分类名称不能为空'
            },
            cost:{
                required:'价格不能为空'
            },
            goodattr:{
                required:'单位不能为空'
            },
            guige:{
                required:'规格不能为空'
            },
            'img[]':{
                required:'展示图不能为空',
				min:'至少需要上传一张'
            }
		},
        onkeyup:false,
        focusCleanup:true,
        success:"valid",
        submitHandler:function(form){
            $(form).ajaxSubmit({
				type: 'post',
				url: '{:url("Product/productEdit")}',
				success:function(res){
                if(1 == res.code){
                    var index = parent.layer.getFrameIndex(window.name);
                    layer.msg(res.msg, {icon:6, time:1000});
                    setTimeout(function(){
                        parent.location.reload();
                        parent.layer.close(index);
                    }, 1000);
                }else{
                    layer.msg(res.msg, {icon: 5,time:1000});
                }
            }});

        }
    });
});

function dropPic(o, path){
    var id = $(o).parents('.item').attr('id');
    var path = $("."+id).val();
    $("."+id).remove();
    $("#"+id).remove();
    $.post('{:url("Pub/dropPic")}', {path:path},function(){

    });
}

</script>
</body>
</html>